package com.guqj.nio.netty.tcp;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.util.Date;

/**
 * @Description 服务端消息处理
 * @Title TcpServerHandler
 * @date 2016年11月17日
 */
public class TcpServerHandler extends SimpleChannelInboundHandler<Object> {

	private int counter;

	@Override
	protected void messageReceived(ChannelHandlerContext ctx, Object msg) throws Exception {
		System.out.println("服务器 messageReceived");
	}

	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
		System.out.println("服务器接收到客户消息请求");
		String body = (String) msg;
		System.out.println("The time server receive order :  [" + body + "], the counter is " + ++counter);
		String currentTime = "QUERY TIME ORDER".equalsIgnoreCase(body) ? new Date(System.currentTimeMillis()).toString() : "错误的消息";
		currentTime = currentTime + "$_";
		ByteBuf res = Unpooled.copiedBuffer(currentTime.getBytes());
		ctx.writeAndFlush(res);
		System.out.println("服务器接处理了客户请求并响应");
	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
		cause.printStackTrace();
		ctx.close();
	}

	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
		System.out.println("客户端已连接");
	}

	@Override
	public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
		ctx.flush();
	}
}
